from common.models.formation import Formation
from common.libs.DataHelper import getCurrentTime
from application import app, db
from flask import Blueprint, request, make_response, redirect
import json, requests

formation_page = Blueprint("formation_page", __name__)

@formation_page.route('/getformation', methods=['GET', 'POST'])
def getformation():
    selecarr = request.json.get('selecarr')
    member = Formation.query.filter(Formation.depid.in_(selecarr)).all()
    rts = []
    for item in member:
        temp = dict(id=item.id, department=item.department.name,
                    rank=item.rank, post=item.post,num=item.num,depid=item.depid
                   )
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@formation_page.route('/postformation', methods=['GET', 'POST'])
def postformation():
    type = request.json.get('type')
    depid = request.json.get('depid')
    print(depid)
    post = request.json.get('post')
    rank = request.json.get('rank')
    num = request.json.get('num')

    if type == 1:
        id = request.json.get('id')
        formation = Formation.query.filter_by(id=id).first()
        formation.depid = depid
        formation.rank = rank
        formation.num = num
        formation.post = post
        formation.updated_time = getCurrentTime()
        db.session.commit()
        return json.dumps({"msg": "编制信息修改成功", "id": id}, ensure_ascii=False)
    else:
        formation = Formation()
        formation.depid = depid
        formation.rank = rank
        formation.num = num
        formation.post = post
        formation.created_time = getCurrentTime()
        db.session.add(formation)
        db.session.flush()
        db.session.commit()
        id = formation.id
        return json.dumps({"msg": "编制信息添加成功", "id": id},
                          ensure_ascii=False)


@formation_page.route('/deleteformation', methods=['GET', 'POST'])
def deleteformation():
    id = request.json.get('id')
    formation = Formation.query.filter_by(id=id).delete()
    db.session.commit()
    return json.dumps({"msg": "编制信息删除成功"}, ensure_ascii=False)




